package com.editso.haier.service;

import com.editso.haier.dao.CommodityDao;
import com.editso.haier.dao.ShoppingCarDao;
import com.editso.haier.dao.UserDao;
import com.editso.haier.entity.Commodity;
import com.editso.haier.entity.ShoppingCar;
import com.editso.haier.entity.User;
import com.editso.haier.result.Result;
import com.editso.haier.result.car.DetailsShoppingCar;
import com.editso.haier.util.Utils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Optional;

@AllArgsConstructor
@Service
public class ShoppingService {

    private ShoppingCarDao shoppingCarDao;

    private CommodityDao commodityDao;

    private UserDao userDao;

    public Result getShopping(String userId){
        return Result.promise(callback-> callback.accept(res->Result.success(
                DetailsShoppingCar.from(shoppingCarDao.findAllByUserId(userId))
        )));
    }

    public Result addShopping(String commodityId, Integer count, String userId){
        return Result.promise(callback -> {
            Commodity commodity = commodityDao.findById(commodityId).orElse(null);
            if (commodity == null){
                callback.reject(null);
                callback.error(res->Result.failure("商品不存在", commodityId));
            }else{
                ShoppingCar shoppingCar = shoppingCarDao.findByCommodityId(commodityId).orElse(null);
                if (shoppingCar != null){
                    shoppingCar.setCount(shoppingCar.getCount() + 1);
                }else{
                    shoppingCar = new ShoppingCar();
                    shoppingCar.setOrderCode(Utils.genSimpleDateCode());
                    shoppingCar.setUser(userDao.findById(userId).orElse(null));
                    shoppingCar.setCount(count);
                    shoppingCar.setCommodity(commodity);
                }
                shoppingCarDao.save(shoppingCar);
            }
        });
    }

    public Result alterShopping(String shoppingId, Integer count){
        return Result.promise(callback->{
            ShoppingCar shoppingCar = shoppingCarDao.findById(shoppingId).orElse(null);
            if (shoppingCar == null){
                callback.reject(null);
                callback.error(err->Result.failure("该单号不存在", shoppingId));
            }else if (count > 0){
                shoppingCar.setCount(count);
                shoppingCarDao.save(shoppingCar);
            }
        });
    }

    public Result deleteShopping(String id) {
        return Result.promise(callback->{
            shoppingCarDao.deleteById(id);
        });
    }
}
